package com.monster.servlet.player;

import com.monster.pojo.Song;
import com.monster.pojo.User;
import com.monster.service.PlayerService;
import com.monster.service.PlayerServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;

@WebServlet("/music/addto_player")
public class AddServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        PlayerService ps = new PlayerServiceImpl();

        String play = request.getParameter("play");
        String key = request.getParameter("type");
        Long id = Long.parseLong(request.getParameter("id"));
        ArrayList<Song> newPlays = ps.getPlaySongs(key, id);
        ArrayList<Song> playSongs = null;

        // 添加信息到user_play表中
        User user = null;
        if (session.getAttribute("user") != null) {
            user = (User) session.getAttribute("user");
            playSongs = ps.listUserPlay(user.getId());
            // 去掉新添加的歌中已存在于播放列表中的歌
            newPlays.removeAll(playSongs);
            playSongs.addAll(newPlays);
            ps.deleteUserPlay(user.getId());
            for (Song song : playSongs) {
                ps.addUserPlay(user.getId(), song.getSongId());
            }
        } else {
            if (session.getAttribute("playSongs") != null) {
                playSongs = (ArrayList<Song>) session.getAttribute("playSongs");
                newPlays.removeAll(playSongs);
                playSongs.addAll(newPlays);
            } else {
                playSongs = newPlays;
            }
        }
        session.setAttribute("playSongs", playSongs);
        if ("1".equals(play)) {
            session.setAttribute("playChange", "play");
        } else {
            session.setAttribute("playChange", "yes");
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
